require 'rexml/document'
require 'rexml/xpath'

module Oos4ruby
class Feed

  attr_reader :previous, :next, :entries, :xml, :size, :total_size
  
  def initialize(entries, xml)
    @entries = entries
    @xml = xml
    @next = Feed.get_link('next', xml)
    @previous = Feed.get_link 'previous', xml
    @self = Feed.get_link 'self', xml
    @size = REXML::XPath.first(xml, "./os:itemsPerPage/text()", XmlNamespaces)
    @total_size = REXML::XPath.first(xml, "./os:totalResults/text()", XmlNamespaces)
  end
  
  def self.get_link(rel, xml)
    link = REXML::XPath.first(xml, "./atom:link[@rel=\"#{rel}\"]", XmlNamespaces)
    if link      
      uri = URI.parse link.attributes['href']
      if uri.absolute?
        return uri
      else
        return URI.parse(OOS_URL).merge(uri)
      end      
    end
  end
  
  def Feed.read(body)

    feed = nil
    begin
      feed = REXML::Document.new(body, { :raw => nil }).root
      
      entries = REXML::XPath.match(feed, "./atom:entry", XmlNamespaces)      

      entries.map! { |entry| Entry.new(entry) }
      feed = Feed.new( entries, feed )
    rescue => ex
      puts ex.message
      puts ex.backtrace.join("\n")        
    end    

    return feed
  end
  
  def self_link
    @self
  end
    
  def self_link?
    !@self.nil?
  end
  
  def previous?    
    !@previous.nil?
  end
  
  def next?    
    !@next.nil?
  end

end
end

